<template>
   <!--文件管理-文件目录设置-其他部门授权弹窗和表单-->
  <a-drawer
    :title="title"
    :maskClosable="true"
    width="650"
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
    style="overflow: auto; padding-bottom: 53px"
  >
    <a-form>
      <a-form-item>
        <a-tree
          title="title"
          @check="onCheck"
          @expand="onExpand"
          @select="onTreeNodeSelect"
          :checkedKeys="checkedKeys"
          :treeData="treeData"
          :selectedKeys="selectedKeys"
          :expandedKeys="expandedKeysss"
          :checkStrictly="checkStrictly"
        >
          <template #title="data">
            <div v-if="data.isUser">
            <div style='display: flex; flex-direction: row;' >
              <a-icon type="user" style='line-height: 26px'/>
              <span style='width: 4rem'>{{ data.realname }}</span>
              <div>
                <a-checkbox-group  :options="options" @change="(c) => {onChange(c,data.id)}"  :value="quanxianValue(data.id)" >
                </a-checkbox-group>
              </div>
            </div>
            </div>
            <!-- ({{data.children.length || 0}}人) -->
            <div v-else>{{data.title}} </div>
          </template>
          <!-- <a-checkbox-group @change="onChange" v-model="checkboxChecked" v-if="treeData.length > 0">
          <a-col :span="24" v-for="(item, index) in treeData" :key="index" >
            <a-checkbox :value="item.id">{{item.isUserList}}0000000{{ item.realname }}</a-checkbox>
          </a-col>
        </a-checkbox-group> -->
        </a-tree>
      </a-form-item>
    </a-form>

    <div class="drawer-bootom-button">
      <!-- <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
          <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
          <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
          <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          树操作 <a-icon type="up" />
        </a-button>
      </a-dropdown> -->
      <a-popconfirm title="确定放弃编辑？" @confirm="close" okText="确定" cancelText="取消">
        <a-button style="margin-right: 0.8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem"
        >仅保存</a-button
      >
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </div>

    <!-- <role-datarule-modal ref="datarule"></role-datarule-modal> -->
  </a-drawer>
</template>
<script>
import {
  queryUserOtherTreeList,
  queryPermissionTreeList,
  submitPermission,
  queryTreeListForRole,
  queryRolePermission,
  saveRolePermission,
} from '@/api/api'
import { getAction } from '../../../../api/manage'
// import RoleDataruleModal from './RoleDataruleModal.vue'
const options = [
  { label: '查看', value: '0' },

]
// { label: '添加/修改', value: '1' },
export default {
  name: 'RoleModal',
  components: {
    // RoleDataruleModal
  },
  data() {
    return {
      roleId: '',
      id: '',
      userids: '',
      type: '',
      dataInfo1:[],
      treeData: [],
      treeData1: [],
      treeData2: [],
      checkboxChecked: [],
      defaultCheckedKeys: [],
      checkedKeys: [],
      expandedKeysss: [],
      allTreeKeys: [],
      autoExpandParent: true,
      checkStrictly: true,
      title: '部门权限配置',
      visible: false,
      loading: false,
      selectedKeys: [],
      options,
      quanxian: {
        '1598151649869791234': 1
      },
    }
  },
  methods: {
    quanxianValue(userId) {
      const q = this.quanxian[userId]
      // console.log('b',this.quanxian);
      // console.log('dsb', q)
      if (q == "0") {
        // 无权限
        return ["0"]
      }
      if (q == "1") {
        return ["0", "1"]
      }

      if (q == "2") {
        return []
      }
      return []
    },
    onChange(checkedValues, uId) {
      if (checkedValues.length <= 0){
        this.quanxian = {
          ...this.quanxian,
          [uId]: '2'
        }
        return
      }
      if (checkedValues.length == 1){
        // console.log('fsd2',this.quanxian);
        this.quanxian = {
          ...this.quanxian,
          [uId]: '0'
        }
        return
      }
      if (checkedValues.length >= 2){
        this.quanxian = {
          ...this.quanxian,
          [uId]: '1'
        }
        return
      }

      if (checkedValues[0] == '1'){
        this.quanxian = {
          ...this.quanxian,
          [uId]: '1'
        }
        return
      }

      if (checkedValues[0] == '0'){
        this.quanxian = {
          ...this.quanxian,
          [uId]: '0'
        }
        return
      }
    },
    log(e) {
      // console.log(e)
    },
    onTreeNodeSelect(id) {
      // console.log('onTreeNodeSelect')
      if (id && id.length > 0) {
        this.selectedKeys = id
      }
      // this.$refs.datarule.show(this.selectedKeys[0],this.roleId)
    },
    onCheck(o) {
      // console.log({ o })
      if (this.checkStrictly) {
        this.checkedKeys = o.checked
      } else {
        this.checkedKeys = o
      }
    },
    show(dataInfo) {

      this.visible = true
      this.dataInfo1=dataInfo
      this.id = dataInfo.id
      this.loadData(this.id)
    },
    close() {
      this.reset()
      this.$emit('close')
      this.visible = false
    },
    onExpand(expandedKeys) {
      // console.log('onExpand')
      this.expandedKeysss = expandedKeys
      this.autoExpandParent = false
    },
    reset() {
      this.expandedKeysss = []
      this.checkedKeys = []
      this.defaultCheckedKeys = []
      this.loading = false
    },
    expandAll() {
      this.expandedKeysss = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeysss = []
    },
    checkALL() {
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      //this.checkedKeys = this.defaultCheckedKeys
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    handleCancel() {
      this.close()
    },
    handleSubmit(exit) {

      let u0 = []
      let u1 = []
      let u2 = []

      let userList = []
      var mergeUserListAndChildren = (arr = []) => {
        if (arr.length > 0){
          arr.forEach((item, index) => {
            if (!!item.children && item.children.length > 0){
              item.children.map(item => {
                if (item.isUser == 1){
                  userList.push({id: item.id , username: item.realname})
                }
              })
              mergeUserListAndChildren(item.children)
            }
          })
        }
      }
      mergeUserListAndChildren(this.treeData)

      userList.forEach((item) => {

        if(this.quanxian[item.id] == 0){
          u0.push(item.id)
          return
        }
        if(this.quanxian[item.id] == 1){
          u1.push(item.id)
          return
        }
        if(this.quanxian[item.id] == 2){
          u2.push(item.id)
         return
        }
        u2.push(item.id)
      })

      let postData = [{
        userids: u0.join(','),
        type: 0,
        id: this.id,
      },{
        userids: u1.join(','),
        type: 1,
        id: this.id,
      },{
        userids: u2.join(','),
        type: 2,
        id: this.id,
      }]

      // console.log({ postData })
      // return
      // 已经整理完了， 数据提交上去就可以了
      // console.log("打开 DirectoryOtherRoleModal.vue 看 297行， 数据已经整理好了，postData 传给接口就可以了")


      // if (!this.dataruleChecked || this.dataruleChecked.length == 0) {
      //   this.$message.warning('请注意，现未勾选任何人员!')
      // }
      let that = this
      // console.log('fdsf',that.dataInfo1);
      // that.id=that.dataInfo1.id
      // let params = {
      //   id: that.id,//文件目录id
      //   userids: '',//选择中用户id，用逗号隔开
      //   type: '',//0查看 1 查看 添加  2 没选
      // }
      that.loading = true
      // console.log('请求参数：',postData)
      submitPermission(postData).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loading = false
          if (exit) {
            that.close()
          }
        } else {
          that.$message.error(res.message)
          that.loading = false
          if (exit) {
            that.close()
          }
        }
        this.loadData()
      })
    },
    loadData(id) {
      var that = this
      queryUserOtherTreeList().then((res) => {

        var mergeUserListAndChildren = (arr = []) => {
          if (arr.length > 0){
            let tmp = []
            arr.forEach((item, index) => {
              let children = []
              if (!!item.children && item.children.length > 0){
                children = mergeUserListAndChildren(item.children.map( cItem => {
                  return {
                    ...cItem,
                    isLeaf: false,
                    title: cItem.title
                  }
                }))
              }
              if (!!item.userList && item.userList.length > 0){
                children = children.concat(item.userList.map(item => ({...item, key: item.id, isUser: 1, selectable: false})))
              }
              tmp.push({
                ...item,
                children
              })
            })
            return tmp
          }
          return  []
        }
        this.treeData = mergeUserListAndChildren(res.result)
      })
      getAction(`/system/sysOrgFile/querySysUserFileById?id=${id}`).then((res) => {
        this.quanxian = res.result
        // console.log('quanxian',res.result);
      })
    },
  },
  watch: {
    visible() {
      if (this.visible) {
        //this.loadData()
      }
    },
  },
}
</script>
<style lang="less" scoped>
.drawer-bootom-button {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>